package org.clipjoint.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.lang3.StringUtils;
import org.clipjoint.dao.AdminDao;
import org.clipjoint.entity.Admin;
import org.clipjoint.util.DataSourceUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 陈光耀
 * @date 2021/2/22
 */
public class AdminDaoImpl implements AdminDao {

    //登录
    @Override
    public Admin selectOne(Admin admin) throws SQLException {

        QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());

        // 动态sql
        String sql = "select * from admin where 1 = 1";
        List<Object> params = new ArrayList<>();
        if (StringUtils.isNotBlank(admin.getUsername())) {
            sql += " and username = ?";
            params.add(admin.getUsername());
        }
        if (StringUtils.isNotBlank(admin.getNickname())) {
            sql += " and nickname = ?";
            params.add(admin.getNickname());
        }
        if (StringUtils.isNotBlank(admin.getPassword())) {
            sql += " and password = ?";
            params.add(admin.getPassword());
        }

        // 查询一个结果
        Admin result = qr.query(sql, new BeanHandler<>(Admin.class), params.toArray());

        return result;
    }


    //最后一次登录时间
    @Override
    public int updatellt(Admin admin) throws SQLException {
        QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());

        String sql = "update `admin` set `username` = ? , `password` = ? , `nickname` = ? , `last_login_time` = ? where `id` = ?";

        int result = qr.update(sql, admin.getUsername(), admin.getPassword(), admin.getNickname(), admin.getLast_login_time(), admin.getId());

        return result;
    }


    //修改密码
    @Override
    public int updatePassword(Admin admin) throws SQLException {
        QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());

        String sql = "update admin set `username` = ?, `nickname`= ?, `password` = ?, `last_login_time` = ? where `id` = ?";

        int result = qr.update(sql, admin.getUsername(), admin.getNickname(), admin.getPassword(), admin.getLast_login_time(), admin.getId());

        return result;
    }


    //修改个人信息
    @Override
    public int updateInfo(Admin admin) throws SQLException {

        QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());

        String sql = "update admin set `username` = ?, `nickname`= ?, `password` = ?, `last_login_time` = ? where `id` = ?";

        int result = qr.update(sql, admin.getUsername(), admin.getNickname(), admin.getPassword(), admin.getLast_login_time(), admin.getId());

        return result;
    }
}
